<!-- 个人主页首页信息 -->
<template>
  <div ref="centreHome">
    <div class="grid m-0 p-0">
      <!-- 用户基本信息：昵称、简介、等级 -->
      <div class="col-12">
        <div class="centre__user__basicinfo">
          <div class="flex justify-content-center align-items-center text-center">
            <div class="centre__user__basicinfo-info">
              <!-- 头像 -->
              <div class="centre__user__basicinfo-avatar">
                <ImgTextAvatar shape="circle"
                               width="128px"
                               height="128px"
                               :upload="userSelf"
                               upload-text="上传头像"
                               @upload-files="avatarUploadFilesHandler"
                               :image="centreUserMsg.avatar"
                               :label="centreUserMsg.nickname"/>
              </div>
              <!-- 信息 container -->
              <div class="centre__user__basicinfo-msg-container">
                <!-- 个人昵称 -->
                <div class="centre__user__basicinfo-nickname"
                     @mouseenter="centreUserInfoNicknameMouseEnterHandler"
                     @mouseleave="centreUserInfoNicknameMouseLeaveHandler">
                  <div tabindex="0"
                       ref="centreUserNicknameRef"
                       :contenteditable="nicknameContenteditable"
                       @keydown.enter="nicknameEditEnterHandler">
                    {{ centreUserMsg.nickname }}
                  </div>
                  <div v-show="nicknameEditShow && userSelf"
                       class="centre__user__edit ml-2"
                       @click="nicknameEditClickHandler">
                    <i class="pi pi-file-edit" style="cursor: pointer;"></i>
                  </div>
                </div>
                <!-- 粉丝数量和关注数量 -->
                <div class="centre__user__basicinfo-fansfocus">
                  粉丝：{{ centreUserMsg.fansCount }} / 关注：{{ centreUserMsg.focusCount }}
                </div>
                <!-- 用户等级 -->
                <div style="font-family: Blackadder ITC, serif; font-weight: 700; color: rgba(255,120,120,0.74)">
                  Level {{ centreUserMsg.level }}
                </div>
                <!-- 个人简介 -->
                <div class="centre__user__basicinfo-desc"
                     @mouseenter="centreUserInfoDescMouseEnterHandler"
                     @mouseleave="centreUserInfoDescMouseLeaveHandler">
                  <div tabindex="1"
                       ref="centreUserDescRef"
                       :contenteditable="descContenteditable"
                       @keydown.enter="descEditEnterHandler"
                       @input="descInputHandler">
                    {{ centreUserMsg.desc }}
                  </div>
                  <div v-show="descEditShow && userSelf"
                       class="centre__user__edit ml-2" @click="descEditClickHandler">
                    <i class="pi pi-file-edit" style="color: #000000; cursor: pointer;"></i>
                  </div>
                </div>
                <!-- 未关注: p-button-danger -->
                <Button v-if="!userSelf"
                        class="p-button-raised p-button-secondary p-button-text"
                        :loading="focusLoading"
                        @click="focusHandler"
                        :class="`${centreUserMsg.fans ? 'p-button-danger' : 'p-button-secondary'}`"
                        :label="`${centreUserMsg.fans ? '取消关注' : '点击关注'}`"></Button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 基本统计 -->
      <div class="col-12">
        <h1>数据统计</h1>
        <!-- 注册时间 -->
        <div class="centre__info">
          <!-- 图标 -->
          <div class="centre__info-icon">
            <svg class="icon"
                 style="margin-right: 5px;"
                 viewBox="0 0 1024 1024"
                 width="32" height="32">
              <path
                  d="M384 512H64v-128h320V256l192 192-192 192zM1024 0v832l-384 192v-192H256v-256h64v192h320V192l256-128H320v256H256V0z"
                  fill="white"></path>
            </svg>
          </div>
          <!-- 入驻时间desc -->
          <div class="centre__info-desc">
            入驻时间
          </div>
          <!-- 时间 -->
          <div class="centre__info-content">
            {{ centreUserMsg.registerTime }}
          </div>
        </div>
        <!-- 发布的文章数量 -->
        <div class="centre__info">
          <!-- 图标 -->
          <div class="centre__info-icon">
            <svg class="icon" viewBox="0 0 1024 1024"
                 width="32" height="32">
              <path
                  d="M321.1264 194.56H165.888c-15.0528 0-26.8288 11.776-26.8288 26.8288v581.12c0 15.0528 11.776 26.8288 26.8288 26.8288h155.2384c15.0528 0 26.8288-11.776 26.8288-26.8288V221.3888c0-15.0528-12.288-26.8288-26.8288-26.8288z m-26.8288 581.12h-101.4784v-527.36h101.4784v527.36z m591.36-25.7024L736.8704 257.9456c-4.4032-14.0288-19.2512-21.9136-33.28-17.7152l-126.2592 38.0928v-56.9344c0-15.0528-11.776-26.8288-26.8288-26.8288H395.264c-15.0528 0-26.8288 11.776-26.8288 26.8288v581.12c0 15.0528 11.776 26.8288 26.8288 26.8288h155.2384c15.0528 0 26.8288-11.776 26.8288-26.8288V451.8912l108.544 358.2976c4.1984 14.2336 19.0464 22.4256 33.28 18.2272l148.7872-45.1584c6.9632-2.1504 12.3904-6.4512 16.0768-12.9024s3.7888-13.9264 1.6384-20.3776z m-361.984 25.7024h-101.4784v-527.36h101.4784v527.36z m205.6192-6.9632l-133.12-440.4224 97.1776-29.4912 133.2224 440.4224-97.28 29.4912z"
                  fill="#ffffff"></path>
            </svg>
          </div>
          <!-- 发布问题desc -->
          <div class="centre__info-desc">
            发布文章
          </div>
          <!-- 发布数量 -->
          <div class="centre__info-content">
            {{ centreUserMsg.detailCount }}篇
          </div>
        </div>
        <!-- 提问的问题数量 -->
        <div class="centre__info">
          <!-- 图标 -->
          <div class="centre__info-icon">
            <svg class="icon" viewBox="0 0 1024 1024"
                 width="32" height="32">
              <path
                  d="M162.1 858.49c-4.3 0-8.64-0.83-12.79-2.55-12.5-5.17-20.57-17.27-20.57-30.79V182.17c0-9.21 7.45-16.66 16.66-16.66h733.2c9.21 0 16.66 7.45 16.66 16.66v516.57c0 9.21-7.45 16.66-16.66 16.66H318.94L185.63 848.71c-6.4 6.4-14.87 9.78-23.53 9.78z m-0.03-659.66v626.31l138.19-138.19c3.12-3.12 7.36-4.88 11.78-4.88h549.9V198.83H162.07z"
                  fill="#ffffff"></path>
              <path
                  d="M525.35 520.47h-46.73v-17.72c-1.08-30.06 12.89-54.77 41.89-74.11 29-21.48 42.94-42.42 41.89-62.83-3.22-26.83-19.33-41.35-48.33-43.51-28.86-0.86-48.83 12.5-59.88 40.11-4.82 12.05-17.91 18.64-30.61 15.95-16.49-3.5-26.19-21.17-19.74-36.74 18.98-45.8 58.4-67.8 118.28-66.03 61.22 3.22 94.5 31.7 99.88 85.4 2.14 33.29-17.19 62.83-58 88.61-26.86 17.18-39.22 36.52-37.05 58 0.01 2.15-1.6 12.87-1.6 12.87z m-20.79 91.83h-3.55c-15.04 0-27.23-12.19-27.23-27.23v-1.93c0-15.04 12.19-27.23 27.23-27.23h3.55c15.04 0 27.23 12.19 27.23 27.23v1.93c0 15.04-12.19 27.23-27.23 27.23z"
                  fill="#ffffff"></path>
            </svg>
          </div>
          <!-- 卡片 desc -->
          <div class="centre__info-desc">
            提问的问题
          </div>
          <!-- 卡片 content -->
          <div class="centre__info-content">
            {{ centreUserMsg.questionCount }}个问题
          </div>
        </div>
        <!-- 回答的问题数量 -->
        <div class="centre__info">
          <!-- 图标 -->
          <div class="centre__info-icon">
            <svg class="icon" viewBox="0 0 1024 1024"
                 width="32" height="32">
              <path
                  d="M337.856 576l284.288 0L480 294.592 337.856 576zM480 64C214.848 64 0 278.848 0 544S214.848 1024 480 1024 960 809.152 960 544 745.152 64 480 64zM751.424 764.032c-14.784 8.256-33.216 2.24-41.152-13.44L654.464 640 305.536 640l-55.872 110.592c-7.936 15.68-26.304 21.696-41.152 13.44-14.784-8.32-20.352-27.776-12.416-43.392l61.888-122.496c0.896-2.624 2.176-4.928 3.648-7.232l187.776-371.776c1.472-9.472 6.464-18.24 15.168-23.104C469.504 193.28 474.752 192.64 480 192.896 485.248 192.64 490.496 193.28 495.424 195.968c8.704 4.864 13.696 13.632 15.168 23.104l187.776 371.776c1.472 2.304 2.752 4.608 3.648 7.232l61.888 122.496C771.84 736.256 766.272 755.712 751.424 764.032z"
                  fill="#ffffff"></path>
            </svg>
          </div>
          <!-- 回答desc -->
          <div class="centre__info-desc">
            回答的问题
          </div>
          <!-- 回答问题的数量 -->
          <div class="centre__info-content">
            {{ centreUserMsg.answerCount }}个
          </div>
        </div>
        <!-- 上传文件数量 -->
        <div class="centre__info">
          <!-- 图标 -->
          <div class="centre__info-icon">
            <svg class="icon" viewBox="0 0 1024 1024" width="32" height="32">
              <path
                  d="M736 256a64 64 0 1 0-64 64 64 64 0 0 0 64-64z m64 0a128 128 0 1 1-128-128 128 128 0 0 1 128 128zM288 512a64 64 0 1 0-64 64 64 64 0 0 0 64-64z m64 0a128 128 0 1 1-128-128 128 128 0 0 1 128 128z m480 256a96 96 0 1 0-96 96 96 96 0 0 0 96-96z m64 0a160 160 0 1 1-160-160 160 160 0 0 1 160 160z"
                  fill="#ffffff"></path>
              <path
                  d="M334.4 476.48a32 32 0 1 1-28.8-56.96l256-128a32 32 0 1 1 28.8 56.96z m-30.08 95.36a32 32 0 0 1 32-55.68l288 160a32 32 0 1 1-32 55.68z"
                  fill="#ffffff"></path>
            </svg>
          </div>
          <!-- 文件 desc -->
          <div class="centre__info-desc">
            分享文件数量
          </div>
          <!-- 文件数量 -->
          <div class="centre__info-content">
            {{ centreUserMsg.fileCount }}
          </div>
        </div>
        <!-- 天气预报 -->
        <div id="he-plugin-standard"></div>
      </div>
      <!-- 关注的用户 -->
      <div class="col-12 mt-5">
        <h1>Ta 关注的用户</h1>
        <!-- empty -->
        <div class="text-center m-5" v-if="centreFocusMsg.length === 0">
          <div>
            <svg class="icon" viewBox="0 0 1024 1024" width="128" height="128">
              <path
                  d="M106.97251697 619.07623114h289.80414734c11.63872078 0 21.53163343 9.89291266 21.53163343 21.53163345 0 51.21037142 40.73552271 91.3639581 92.52783018 91.3639581s92.52783017-40.15358668 92.52783018-91.3639581c0-11.63872078 9.89291266-21.53163343 21.53163344-21.53163345h288.05833923c8.72904058 0 16.29420908 5.23742435 19.78582532 12.80259287-4.65548831-15.71227305-12.80259285-32.00648214-13.96646493-34.3342263 0-0.58193603-0.58193603-0.58193603-0.58193604-0.58193603l-92.52783018-146.6478818c0-0.58193603-0.58193603-0.58193603-0.58193605-1.16387207-1.74580811-1.74580811-15.71227305-19.78582532-32.00648212-29.09680195-16.87614513-9.89291266-40.15358668-11.63872078-43.06326688-11.63872078h-494.64563303c-4.07355227 0-23.8593776 0.58193603-39.57165064 9.89291266-15.71227305 9.89291266-27.35099383 26.76905779-28.5148659 28.51486591 0 0-0.58193603 0.58193603-0.58193603 1.16387208l-77.97942921 138.50077725c-2.32774415 3.49161624-9.89291266 16.87614513-16.29420909 37.82584251 4.07355227-2.9096802 8.72904058-5.23742435 14.54840098-5.23742435z"
                  fill="#2C2C2C"></path>
              <path
                  d="M937.3952444 670.28660257c0-1.74580811-1.16387208-16.87614513-4.07355228-31.4245461v2.32774415c0 11.63872078-9.31097662 21.53163343-21.53163344 21.53163343h-267.69057785l-2.90968021 11.05678476c-15.13033701 59.93941199-69.25038862 101.25687076-130.93560873 101.25687075-62.26715616 0-116.38720777-41.8993948-131.51754478-101.25687075l-2.9096802-11.05678476H106.39058092c-8.72904058 0-15.71227305-5.23742435-19.20388928-12.22065681-1.16387208 10.4748487-1.16387208 18.62195325-1.16387208 22.11356949v157.12273048c0 2.9096802 1.74580811 26.76905779 18.62195325 42.48133083 16.87614513 15.71227305 43.64520291 16.87614513 46.5548831 16.87614514h1.16387208-0.58193603 715.78132778c5.23742435 0 31.4245461-0.58193603 49.46456329-16.87614514 18.0400172-16.29420908 19.20388928-38.40777856 19.2038893-44.80907498l1.16387207-157.12273049zM509.0903198 348.47597308c-16.29420908 0-29.67873798-13.3845289-29.67873798-29.67873798V148.87191176c0-16.29420908 13.3845289-29.67873798 29.67873798-29.67873798s29.67873798 13.3845289 29.67873799 29.67873798v170.50725939c0 16.29420908-13.3845289 29.09680195-29.67873799 29.09680193z m198.44018926-1.16387207c-16.29420908 0-29.67873798-13.3845289-29.67873798-29.67873799 0-6.98323246 2.32774415-13.3845289 6.40129642-18.62195323l67.5045805-83.21685357c5.81936038-6.98323246 13.96646493-11.05678473 23.27744156-11.05678473 6.98323246 0 13.3845289 2.32774415 18.62195324 6.40129643 6.40129643 4.65548831 9.89291266 12.22065682 11.05678474 19.78582531 0.58193603 7.56516851-1.74580811 15.71227305-6.40129642 21.53163344l-67.50458051 83.21685356c-5.81936038 8.14710455-13.96646493 12.22065682-23.27744155 11.63872078z m-393.38876226-1.74580812c-8.72904058 0-17.45808117-4.07355227-23.27744156-11.05678474l-66.34070843-83.7987896c-9.89291266-12.80259285-8.14710455-31.4245461 4.65548831-41.89939479 5.23742435-4.07355227 11.63872078-6.40129643 18.62195325-6.40129643 9.31097662 0 17.45808117 4.07355227 23.27744155 11.05678474l66.34070843 83.79878959c9.89291266 12.80259285 8.14710455 31.4245461-4.65548831 41.8993948-5.23742435 4.07355227-12.22065682 6.40129643-18.62195324 6.40129643z"
                  fill="#2C2C2C"></path>
            </svg>
          </div>
          <div>
            没有关注过任何人哦
          </div>
        </div>
        <!-- 关注用户的基本信息[最多装 4 个 -- 取最新关注] -->
        <div class="centre__focus__users"
             v-for="(item, index) of centreFocusMsg"
             :key="item.nickname + '-' + index"
             @mouseenter="centreFocusUserMouseEnter"
             @mouseleave="centreFocusUserMouseleave">
          <!-- 用户信息 -->
          <div class="centre__focus__users-info">
            <!-- 用户头像 -->
            <div class="centre__focus__users-avatar">
              <ImgTextAvatar :image="item.avatar"
                             :label="item.nickname"
                             shape="circle"
                             height="64px"
                             width="64px"></ImgTextAvatar>
            </div>
            <!-- 用户名 -->
            <div class="centre__focus__users-nickname m-text-overflow-ellipsis-1">
            <span>
              {{ item.nickname }}
            </span>
            </div>
          </div>
          <!-- 等级 -->
          <div class="centre__focus__user-level">
            <div>
              Level {{ item.level }}
            </div>
          </div>
          <!-- 文章信息 -->
          <div class="centre__focus__user-statics">
            <div class="centre__focus__user-statics-item">
              发布了 {{ item.detailCount }} 篇文章
            </div>
            <div class="centre__focus__user-statics-item">
              解答了 {{ item.answerCount }} 个问题
            </div>
            <div class="centre__focus__user-statics-item">
              拥有 {{ item.fansCount }} 个粉丝
            </div>
          </div>
          <!-- 前往主页按钮 -->
          <div class="centre__focus__user-btn">
            <Button class="p-button-outlined p-button-secondary" label="前往主页"
                    @click="router.push(`/centre/${item.nickname}`)"></Button>
          </div>
        </div>
        <!-- 详情更多 -->
        <div class="centre__focus__users"
             v-if="centreFocusMsg.length >= 4"
             style="font-family: Rockwell Extra Bold,serif; font-size: 50px;"
             @click="focusSidebarVisible = true"
             @mouseenter="centreOtherFocusUserMouseEnter"
             @mouseleave="centreOtherFocusUserMouseleave">
          <!-- 用户信息 -->
          <div class="centre__focus__users-info">
            <!-- 用户头像 -->
            <div class="centre__focus__users-avatar">
              👀
            </div>
          </div>
          <!-- 文章信息 -->
          <div>
            查看
          </div>
          <div class="centre__focus__user-statics">
            更多的
          </div>
          <div>
            用户关注
          </div>
          <!-- 箭头 -->
          <div ref="centreFocusArrowNext" class="centre__arrow" style="width: 50px; height: 50px; right: 15px;">
            <div class="relative">
              <div class="absolute arrow__next-line">
              </div>
              <div class="arrow__next absolute"
                   style="right: 1px;">
              </div>
            </div>
          </div>

        </div>
      </div>
      <!-- 文章统计 -->
      <div class="col-12">
        <Chart type="bar" :data="chartData" :options="chartOptions" @loaded="chartLoadedHandler"/>
      </div>
    </div>
    <!-- 用户文章 sidebar -->
    <div>
      <Sidebar v-model:visible="focusSidebarVisible"
               position="top"
               style="height: 80vh;"
               :baseZIndex="10000">
        <div>
          <DataTable v-model:filters="filters"
                     :loading="focusDataLoading"
                     :value="focusPagingData.data"
                     :paginator="true"
                     :rowHover="true"
                     :globalFilterFields="['nickname']"
                     :rows="focusPaging.limit"
                     :totalRecords="focusPagingData.total"
                     @page="focusSidebarPagingHandler"
                     paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                     currentPageReportTemplate="总共关注了 {totalRecords} 用户"
                     class="p-datatable-customers"
                     dataKey="id"
                     filterDisplay="menu"
                     responsiveLayout="scroll">
            <template #header>
              <div class="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
              <span class="p-input-icon-left">
                <i class="pi pi-search"/>
                <InputText v-model="filters['global'].value" placeholder="用户昵称"/>
              </span>
              </div>
            </template>
            <template #empty>
              No customers found.
            </template>
            <template #loading>
              Loading customers data. Please wait.
            </template>
            <!-- 用户昵称 column -->
            <Column field="nickname" header="用户昵称" sortable style="min-width: 14rem">
              <template #body="{data}">
                <div class="flex justify-content-start align-items-center">
                  <ImgTextAvatar :image="data.avatar"
                                 :label="data.nickname"
                                 shape="circle"/>
                  <span class="ml-2">{{ data.nickname }}</span>
                </div>

              </template>
              <template #filter="{filterModel}">
                <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                           placeholder="Search by name"/>
              </template>
            </Column>
            <!-- 等级 column -->
            <Column field="level" header="用户等级" sortable style="min-width: 14rem">
              <template #body="{data}">
                <div style="background-color: #152d2f; font-family: Brush Script MT, serif; align-content: center; font-size: 16px; color: #ffffff; font-weight: 700;
                          padding: 5px 10px 5px 10px;
                          border-radius: 20px; width:fit-content">
                  <div>
                    Level {{ data.level }}
                  </div>
                </div>
              </template>
              <template #filter="{filterModel}">
                <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                           placeholder="Search by name"/>
              </template>
            </Column>
            <!-- 发布文章 column -->
            <Column field="detailCount" header="发布文章数量" sortable style="min-width: 14rem">
              <template #body="{data}">
                {{ data.detailCount }}
              </template>
              <template #filter="{filterModel}">
                <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                           placeholder="Search by name"/>
              </template>
            </Column>
            <!-- 回答次数 column -->
            <Column field="answerCount" header="回答次数" sortable style="min-width: 14rem">
              <template #body="{data}">
                {{ data.answerCount }}
              </template>
              <template #filter="{filterModel}">
                <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                           placeholder="Search by name"/>
              </template>
            </Column>
            <!-- 粉丝数量 column -->
            <Column field="fansCount" header="粉丝数量" sortable style="min-width: 14rem">
              <template #body="{data}">
                {{ data.fansCount }}
              </template>
              <template #filter="{filterModel}">
                <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                           placeholder="Search by name"/>
              </template>
            </Column>
            <!-- 前往主页按钮 -->
            <Column headerStyle="width: 4rem; text-align: center" bodyStyle="text-align: center; overflow: visible">
              <template #body="{data}">
                <Button type="button" label="前往主页" @click="focusSidebarClickHandler(data.nickname)"></Button>
              </template>
            </Column>
          </DataTable>
        </div>
      </Sidebar>
    </div>
  </div>
</template>

<script lang="ts" setup>
/** JS */
import {ref, Ref, reactive, onMounted, nextTick, watch, defineEmits, onUpdated} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {FilterMatchMode, FilterOperator} from 'primevue/api';
import {useConfirm} from 'primevue/useconfirm';
import {
  UserService,
  UserMsg,
  UserCentre7DaysStatics,
  UserFocusOrFansPaging,
  PaginatorResponseResult
} from '@/utils/ApiRequest';
import {ExecFunction} from '@/utils/YzjUtils';
import Cache from '@/utils/Cache';
import toast from '@/utils/Toast';
/** 组件 */
import ImgTextAvatar from '@/components/avatar/ImgTextAvatar.vue';
import DataTable from 'primevue/datatable';
import Sidebar from 'primevue/sidebar';
import Chart from 'primevue/chart';
import Column from 'primevue/column';

const cache = new Cache(),
    route = useRoute(),
    router = useRouter(),
    userMsg: UserMsg = cache.get('userMsg'),
    userService = new UserService(),
    $confirm = useConfirm(),
    emits = defineEmits(['chartLoaded', 'onUpdated'])
/** 元素钩子 */
const centreFocusArrowNext = ref(null);

/** 统计图表 */
let chartStatics: UserCentre7DaysStatics = reactive({
  detailStatics: {},
  questionStatics: {},
  answerStatics: {}
});
let chartData = reactive({
      labels: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      datasets: [
        {
          type: 'line',
          label: '回答的问题',
          borderColor: '#42A5F5',
          borderWidth: 2,
          fill: false,
          data: [0]
        },
        {
          type: 'bar',
          label: '提问问题',
          backgroundColor: '#FFA726',
          data: [0]
        },
        {
          type: 'bar',
          label: '发布文章',
          backgroundColor: '#66BB6A',
          data: [0],
          borderColor: 'white',
          borderWidth: 2
        },
      ]
    }),
    chartOptions = reactive({
      plugins: {
        legend: {
          labels: {
            color: '#495057'
          }
        }
      },
      scales: {
        x: {
          ticks: {
            color: '#495057'
          },
          grid: {
            color: '#ebedef'
          }
        },
        y: {
          ticks: {
            color: '#495057'
          },
          grid: {
            color: '#ebedef'
          }
        }
      }
    });
const chartLoadedHandler = (ev: any) => {
  nextTick(() => {
    if (centreHome.value) {
      let element = centreHome.value as HTMLElement;
      emits('onUpdated', element);
    }
  })
}

/** 修改 nickname 、desc 和头像时确认弹出的提示框 */
const message = ref(''), header = ref('');
const openConfirm = (header: string, message: string, accept: () => void, reject: () => void) => {
  $confirm.require({
    message: message,
    header: header,
    icon: 'pi pi-exclamation-triangle',
    accept: () => {
      accept();
    },
    reject: () => {
      reject();
    }
  });
}

/** 修改 nickname */
const centreUserNicknameRef = ref(null);
let nicknameContenteditable = ref(false);
const nicknameEditClickHandler = () => {
      if (centreUserNicknameRef.value) {
        let element = centreUserNicknameRef.value as HTMLElement;
        element.focus();
      }
      nicknameContenteditable.value = true;
    },
    /*    nicknameInputHandler = (ev: InputEvent) => {
          // 使用 ev.data 的话中文会触发2次
          if (ev.data) {
            tempNickname.value = (ev.target as HTMLElement).innerText.trim();
          }
        },*/
    nicknameEditEnterHandler = (ev: KeyboardEvent) => {
      ev.preventDefault();
      let execFunc = new ExecFunction();
      if (centreUserNicknameRef.value) {
        let element = centreUserNicknameRef.value as HTMLElement;
        let name = (ev.target as HTMLElement).innerText.trim();
        // 值空
        if (!name || name.trim() === '') {
          toast.error('不行不行！', '你这啥也没有肯定不行啊，至少3字最多10字哦！', 1500);
          return;
        } else if (name.trim().length < 3) {
          toast.warn('太短了哦', '这太短啦，最少3字，最多10字哦！', 1500);
          return;
        } else if (name.trim().length > 10) {
          toast.warn('太长啦', '太长了，最多10字，10字!', 1500);
          return;
        }
        openConfirm('修改提示', '昵称7天只能修改一次，确认当前昵称吗？', async () => {
          element.blur();
          nicknameContenteditable.value = false;
          let record = await execFunc.record(centreUserMsg.value.nickname).exec(async () => {
            await userService.update({nickname: name});
            userMsg.nickname = name;
            centreUserMsg.value.nickname = name;
            cache.set('userMsg', userMsg);
            toast.success('成功啦！~', `修改昵称成功啦，3天之后才能再改哦(●'◡'●)`, 3000);
          });
          if (record) {
            userMsg.nickname = record;
            centreUserMsg.value.nickname = record;
            element.innerText = record;
            cache.set('userMsg', userMsg);
          }
        }, () => {
          element.innerText = centreUserMsg.value.nickname;
        })
      }
    }
/** 修改 desc */
const centreUserDescRef = ref(null);
let descContenteditable = ref(false), tempDesc = ref('');
const descEditClickHandler = () => {
      if (centreUserDescRef.value) {
        let element = centreUserDescRef.value as HTMLElement;
        element.focus();
      }
      descContenteditable.value = true;
    },
    descInputHandler = (ev: InputEvent) => {
      // 使用 ev.data 的话中文会触发2次
      if (ev.data) {
        tempDesc.value = (ev.target as HTMLElement).innerText.trim();
      }
    },
    descEditEnterHandler = (ev: KeyboardEvent) => {
      ev.preventDefault();
      let execFunc = new ExecFunction();
      if (centreUserNicknameRef.value) {
        let element = centreUserNicknameRef.value as HTMLElement;
        let desc = (ev.target as HTMLElement).innerText.trim();
        // 值空
        if (!desc || desc.trim() === '') {
          toast.error('这样不可以的哦！', "既然打算填，何不简要的介绍一下自己呢？(●'◡'●)", 1500);
          return;
        }
        openConfirm('修改提示', '昵称7天只能修改一次，确认当前昵称吗？', async () => {
          element.blur();
          nicknameContenteditable.value = false;
          let record = await execFunc.record(centreUserMsg.value.desc).exec(async () => {
            await userService.update({desc: desc});
            userMsg.desc = desc;
            centreUserMsg.value.desc = desc;
            cache.set('userMsg', userMsg);
            toast.success('成功啦！~', `修改简介成功啦，3天之后才能再改哦(●'◡'●)`, 3000);
          });
          if (record) {
            userMsg.desc = record;
            centreUserMsg.value.desc = record;
            element.innerText = record;
            cache.set('userMsg', userMsg);
          }
        }, () => {
          element.innerText = centreUserMsg.value.nickname;
        })
      }
      descContenteditable.value = false;
    }

/** 上传头像 */
const avatarUploadFilesHandler = async (files) => {
  let execFunc = new ExecFunction();
  let record = await execFunc.record(centreUserMsg.value.avatar).exec(async () => {
    let data = {file: files[0]};
    let res = await userService.update(data)
    userMsg.avatar = res.data.avatar;
    centreUserMsg.value.avatar = res.data.avatar;
    cache.set('userMsg', userMsg);
    toast.success('更换头像成功😄', `3天之后才能再次更换哦(●'◡'●)`, 3000);
  });
  if (record) {
    userMsg.avatar = record;
    centreUserMsg.value.avatar = record;
    cache.set('userMsg', userMsg);
  }
}

/** 查看关注列表 */
const focusSidebarVisible = ref(false);
const focusPagingData: Ref<PaginatorResponseResult<UserMsg> | object> = ref([]),
    focusPaging: UserFocusOrFansPaging = reactive({
      page: 0,
      limit: 10,
      fans: false,
      focus: true,
      nickname: ''
    }),
    filters = reactive({
      global: {value: null, matchMode: FilterMatchMode.CONTAINS},
      nickname: {operator: FilterOperator.AND, constraints: [{value: null, matchMode: FilterMatchMode.STARTS_WITH}]},
    }),
    focusDataLoading = ref(true);
const getPagingFocus = async () => {
      let res = await userService.getUserFocusOrFansByPaging(focusPaging);
      focusDataLoading.value = false;
      focusPagingData.value = res.data;
    },
    focusSidebarClickHandler = async (nickname) => {
      await router.push(`/centre/${nickname}`);
      focusSidebarVisible.value = false;
    },
    focusSidebarPagingHandler = async (ev) => {
      focusPaging.page = ev.page;
      await getPagingFocus();
    }
const execFunction = new ExecFunction();
const focusLoading = ref(false);
const focusHandler = async () => {
      // 阻塞 fn
      execFunction.blockageFunction(async () => {
        focusLoading.value = true;
        let res = await userService.update({
          focus: centreUserMsg.value.nickname
        });
        if (res) {
          let lastFocus = res.data.toFocus;
          if (lastFocus) {
            toast.success('关注成功', `很高兴你能在这里找到喜欢的人呢~(￣▽￣)"`, 3000)
            if (centreUserMsg.value.fansCount) {
              centreUserMsg.value.fansCount += 1;
            }
          } else {
            toast.warn('取关成功', `世上又多了一个失去粉丝的人呢~/(ㄒoㄒ)/~~`, 3000)
            if (centreUserMsg.value.fansCount) {
              centreUserMsg.value.fansCount -= 1;
            }
          }
          centreUserMsg.value.fans = lastFocus
        }
        focusLoading.value = false;
      }, (time) => {
        toast.error('捏🐎🐎滴~~', `点这么快干嘛哟？请${(time / 1000).toFixed(2)}秒后重试~~混蛋🤬`, 3000)
      }, 1500);
}
watch(focusSidebarVisible, (n) => {
  if (n) {
    // 打开时发送请求
    getPagingFocus();
  }
})

/** 箭头动画处理 */
const centreFocusActive = (active: boolean) => {
  let nextArrow = centreFocusArrowNext.value;
  if (nextArrow) {
    let element = nextArrow as HTMLElement;
    if (element.childNodes[0].childNodes) {
      let centreInfoDoc = document.getElementsByClassName('centre__focus__users');
      let first = centreInfoDoc.item(0);
      if (first) {
        let line = element.childNodes[0].childNodes[0] as HTMLElement,
            arrow = element.childNodes[0].childNodes[1] as HTMLElement;
        line.style.transform = active ? 'translateY(3px)' : 'translateY(0px)';
        line.style.width = active ? `${first.clientWidth - 35}px` : '20px';
        line.style.borderBottomColor = active ? '#ffffff' : '#000000';
        arrow.style.width = active ? '13px' : '7px';
        arrow.style.height = active ? '13px' : '7px';
        arrow.style.borderTopColor = active ? '#ffffff' : '#000000';
        arrow.style.borderRightColor = active ? '#ffffff' : '#000000';
      }
    }
  }
}

/** 用户昵称移入时*/
const nicknameEditShow = ref(false), descEditShow = ref(false);
const centreUserInfoNicknameMouseEnterHandler = (ev: MouseEvent) => {
      nicknameEditShow.value = true;
    },
    /** 用户昵称移出时*/
    centreUserInfoNicknameMouseLeaveHandler = (ev: MouseEvent) => {
      nicknameEditShow.value = false;
    },
    centreUserInfoDescMouseEnterHandler = () => {
      descEditShow.value = true;
    },
    centreUserInfoDescMouseLeaveHandler = () => {
      descEditShow.value = false;
    }

/** 关注列表卡片鼠标移入时 */
const centreFocusUserMouseEnter = (ev: MouseEvent) => {
      let target = ev.target;
      if (target) {
        let element: HTMLElement = target as HTMLElement;
        let parent = element.parentElement;
        if (parent) {
          // 移除同类元素
          for (let child of parent.children) {
            if (child.classList && child.classList.contains('centre__focus__users-active')) {
              child.classList.remove('centre__focus__users-active');
            }
          }
        }
        element.classList.add('centre__focus__users-active');
      }
    },
    /** 关注列表卡片鼠标移出时 */
    centreFocusUserMouseleave = (ev: MouseEvent) => {
      let target = ev.target;
      if (target) {
        let element: HTMLElement = target as HTMLElement;
        element.classList.remove('centre__focus__users-active');
        centreFocusActive(false);
      }
    },
    centreOtherFocusUserMouseEnter = (ev: MouseEvent) => {
      centreFocusUserMouseEnter(ev);
      centreFocusActive(true);
    },
    centreOtherFocusUserMouseleave = (ev: MouseEvent) => {
      centreFocusUserMouseleave(ev);
      centreFocusActive(false);
    }
/** 用户统计信息 */
let nickname: Ref<string> = ref(route.params.nickname as string);
const centreUserMsg: Ref<UserMsg> = ref({
      avatar: '',
      desc: '',
      email: '',
      level: 0,
      focusCount: 0,
      fansCount: 0,
      nickname: '',
    }),
    centreFocusMsg: Ref<UserMsg[]> = ref([]),
    userSelf = ref(false);

/** 校验 nickname */
function validate() {
  if (nickname.value === undefined || nickname.value.trim() === '') {
    if (!userMsg) {
      toast.warn('对不起哦', '要进入个人页面请先登录哦！~', 1500);
      setTimeout(() => {
        router.push({
          path: '/'
        });
      }, 1500);
      return false;
    } else {
      nickname.value = userMsg.nickname;
    }
  }
  return true;
}

/** 构建天气 */
function buildWeather() {
  nextTick(() => {
    let centreInfoDoc = document.getElementsByClassName('centre__focus__users');
    let first = centreInfoDoc.item(0);
    if (first) {
      // 天气插件
      (window as any).WIDGET = {
        "CONFIG": {
          "layout": "2",
          "width": first.clientWidth,
          "height": 270,
          "background": "1",
          "dataColor": "FFFFFF",
          "language": "zh",
          "borderRadius": "5",
          "key": "f78d8df5c8164c5d9b99c26798f3d226"
        },
      };
      let script = document.createElement("script");
      script.type = "text/javascript";
      script.src =
          "https://widget.qweather.net/standard/static/js/he-standard-common.js?v=2.0";
      document.getElementsByTagName("head")[0].appendChild(script);
    }

  })
}

const weeks = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
/** 获取关注列表 -- 4个 */
const getCentreFocus = async () => {
      if (validate()) {
        let res = await userService.getUserCentreFocusList(nickname.value);
        centreFocusMsg.value = res.data;
        // 构造天气组件
        await nextTick(() => {
          buildWeather();
        })
      }
    },
    /** 获取用户信息 */
    getUserMsg = async () => {
      if (validate()) {
        let res = await userService.getUserMsg(nickname.value);
        centreUserMsg.value = res.data;
        if (centreUserMsg.value.registerTime) {
          centreUserMsg.value.registerTime = centreUserMsg.value.registerTime.substring(0, 10);
        }
        userSelf.value = userMsg && userMsg.nickname === centreUserMsg.value.nickname;
      }
    },
    /** 获取图表统计 */
    getStatics = async () => {
      if (validate()) {
        let res = await userService.centreDetailStatics(nickname.value);
        chartStatics = res.data;
        let i = 0;
        for (let chartStaticsKey in chartStatics) {
          let j = 0;
          for (let week of weeks) {
            let data = chartStatics[chartStaticsKey][week];
            if (data) {
              chartData.datasets[i].data[j] = data;
            } else {
              chartData.datasets[i].data[j] = 0;
            }
            j++;
          }
          i++;
        }
      }
    },
    /** 综合以上3个方法 */
    getCentreHomeData = async () => {
      await getCentreFocus();
      await getUserMsg();
      await getStatics();
    }
/** 监听路由变化 */
watch(() => route.params, (n) => {
  nickname.value = n.nickname as string;
  getCentreHomeData();
}, {deep: true})

onMounted(() => {
  if (validate()) {
    getCentreHomeData();
  }
})
const centreHome = ref(null);
onUpdated(() => {
  nextTick(() => {
    if (centreHome.value) {
      let element = centreHome.value as HTMLElement;
      emits('onUpdated', element);
    }
  })

})
</script>

<style lang="less" scoped>
// ------------------------- 用户基本消息 -------------------------
.centre__user__edit {
  cursor: pointer;
}

.centre__user__basicinfo {


  .centre__user__basicinfo-info {
    .centre__user__basicinfo-msg-container {
      margin-top: 15px;
      background-color: var(--root-bg-color);
    }

    .p-button {
      margin-top: 15px;
    }

    .centre__user__basicinfo-avatar-container {
      display: flex;
      justify-content: center;
    }


    .centre__user__basicinfo-fansfocus {
      font-size: 14px;
      color: var(--gray-600);
      margin: 5px;
    }

    .centre__user__basicinfo-nickname {
      display: flex;
      justify-content: center;
      font-size: 24px;
      font-weight: 700;
      transition: .3s all;

    }

    .centre__user__basicinfo-desc {
      display: flex;
      justify-content: center;
      font-size: 12px;
      color: var(--gray-500);
      margin: 5px;
      transition: .3s all;
    }
  }


}

// --------------------------------------------------


// ------------------------- centre 卡片消息样式 -------------------------
.centre__focus__users-active {
  background-color: #2633b3 !important;
  color: white !important;

  .centre__focus__user-btn {
    .p-button {
      background-color: #29aae1 !important;
      color: white !important;
    }
  }
}

.centre__focus__users {
  position: relative;
  margin: 20px 15px 20px 15px;
  background-color: #c1f1ff;
  padding: 20px;
  border-radius: 10px;
  width: 17.3%;
  transition: all .3s ease-in-out;
  display: inline-block;


  &:hover {
    transform: translateY(-10px);
    box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px, rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
    cursor: pointer;
  }

  .centre__focus__users-info {
    display: flex;

    .centre__focus__users-avatar {
      display: inline-block;
    }

    .centre__focus__users-nickname {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22px;
      font-weight: 800;
      font-family: Century Gothic, serif;
      margin-left: 15px;
    }
  }

  .centre__focus__user-level {
    display: flex;
    justify-content: end;

    div {
      background-color: #152d2f;
      font-family: Brush Script MT, serif;
      align-content: center;
      font-size: 16px;
      color: #ffffff;
      font-weight: 700;
      padding: 5px 10px 5px 10px;
      border-radius: 20px;
    }
  }

  .centre__focus__user-statics {
    margin-top: 20px;

    .centre__focus__user-statics-item {
      margin: 5px;
    }
  }

  .centre__focus__user-btn {
    margin-top: 25px;
    margin-bottom: 10px;

    .p-button {
      padding: 5px 20px;
      transition: all .15s !important;
    }

    transition: all .15s !important;
  }

}

// --------------------------------------------------


// ------------------------- centre 卡片消息样式 -------------------------
.centre__info {
  display: inline-block;
  margin: 20px 15px 20px 15px;
  background-color: #f7f8fa;
  border-radius: 10px;
  padding: 25px;
  height: 270px;
  width: 13.333%;

  &:hover {
    transform: translateY(-10px);
    box-shadow: rgba(50, 50, 93, 0.25) 0px 30px 60px -12px, rgba(0, 0, 0, 0.3) 0px 18px 36px -18px;
    cursor: pointer;
  }

  transition: all .3s;

  .centre__info-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #2633b3;
    height: 64px;
    width: 64px;
    border-radius: 32px;

    .icon {
      color: white;
    }
  }

  .centre__info-desc {
    padding-top: 55%;
    color: var(--gray-500);
  }

  .centre__info-content {
    padding-top: 10%;
    font-weight: 800;
    font-size: 24px;
  }
}

// --------------------------------------------------
</style>
